﻿#region License Info

//Component of Cronos Package, http://www.codeplex.com/cronos
//Copyright (C) 2009 Anthony Brockwell

//This program is free software; you can redistribute it and/or
//modify it under the terms of the GNU General Public License
//as published by the Free Software Foundation; either version 2
//of the License, or (at your option) any later version.

//This program is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//GNU General Public License for more details.

//You should have received a copy of the GNU General Public License
//along with this program; if not, write to the Free Software
//Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

#endregion

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using ABMath.ModelFramework.Data;
using ABMath.ModelFramework.Visuals;
using ExtraControlLibrary.Forms;
using PdfSharp;
using PdfSharp.Drawing;
using PdfSharp.Pdf;

namespace ExtraControlLibrary.VisualControls
{
    public partial class ResidualControl : UserControl, IUpdateable
    {
        private readonly ResidualVisual rv;

        public ResidualControl(ResidualVisual rv)
        {
            this.rv = rv;
            rv.AssociatedControl = this;
            InitializeComponent();
            DataHasChanged();
        }

        #region IUpdateable Members

        public void DataHasChanged()
        {
            if (rv == null)
                return;
            if (rv.TheTimeSeries == null)
                return;

            // fill in display Components
            qqPlotBox.Clear(false);
            qqPlotBox.SetMatrix(rv.QuantileMatrix);

            var sb = new StringBuilder(1024);
            sb.AppendLine("Test Results:");
            sb.AppendLine();
            foreach (var test in rv.ResidualTests)
                sb.AppendLine(string.Format("{0}:\t{1}", test.Name(), test.Description()));

            infoTextBox.Text = sb.ToString();
        }

        #endregion

        private void qqPlotBox_MouseClick(object sender, MouseEventArgs e)
        {
            if (rv == null)
                return;

            if (e.Button == MouseButtons.Right)
            {
                // select from a drop-down menu
                var options = new List<string>();
                options.Add("Copy Points to Clipboard");
                options.Add("Export Plot to PDF File");
                Point newLocation = PointToScreen(e.Location);
                var m = new DropMenuForm(newLocation, options);
                m.ShowDialog();
                {
                    switch (m.SelectedIndex)
                    {
                        case -1: // no selection
                            break;
                        case 0: // edit title/description
                            CopyToClipboard();
                            break;
                        case 1: // copy to clipboard w/out dates
                            ExportPlotToPDFFile();
                            break;
                        default:
                            break;
                    }
                }
            }
        }

        /// <summary>
        /// makes a pdf version of the plot
        /// </summary>
        private void ExportPlotToPDFFile()
        {
            if (rv == null)
                return;
            if (rv.QuantileMatrix == null)
                return;

            // get file name
            var saveDialog = new SaveFileDialog();
            saveDialog.Filter = "PDF Files (*.pdf)|*.pdf" + "|All Files (*.*)|*.*";

            // use pdfsharp
            if (saveDialog.ShowDialog() == DialogResult.OK)
            {
                double scale = 1.0;
                var document = new PdfDocument(saveDialog.FileName);
                var page = document.AddPage();
                page.Orientation = PageOrientation.Landscape;
                page.Width *= scale;
                page.Height *= scale;
                var gfx = XGraphics.FromPdfPage(page);
                qqPlotBox.CreatePartition(new Rectangle(0, 0, (int)page.Width, (int)page.Height));
                qqPlotBox.RenderToXGraphics(gfx, (int)Math.Floor(28 * scale), (int)Math.Floor(16 * scale));   // 16, 12
                document.Close();
            }
        }

        /// <summary>
        /// copies qq plot values to clipboard in (x,y) text format
        /// </summary>
        private void CopyToClipboard()
        {
            if (rv == null)
                return;
            if (rv.QuantileMatrix == null)
                return;

            var sb = new StringBuilder(16384);
            for (int i=0 ; i<rv.QuantileMatrix.RowCount ; ++i)
                sb.AppendLine(string.Format("{0:0.0000}\t{1:0.0000}", rv.QuantileMatrix[i, 0], rv.QuantileMatrix[i, 1]));

            Clipboard.SetText(sb.ToString());
        }
    }
}